import { Global, Module } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Redis } from "ioredis";

export const REDIS_CLIENT = Symbol("REDIS_CLIENT");

const redisFactory = {
    provide: REDIS_CLIENT,
    useFactory: (configService: ConfigService): Redis => {
        const host = configService.get<string>("REDIS_HOST", "localhost");
        const port = configService.get<number>("REDIS_PORT", 6379);
        const db = configService.get<number>("REDIS_DB", 14);
        const username = configService.get<string>("REDIS_USERNAME", "");
        const password = configService.get<string>("REDIS_PASSWORD", "");

        return new Redis({
            host,
            port,
            db,
            username: username || undefined,
            password: password || undefined,
        });
    },
    inject: [ConfigService],
};

// @Global() 应该只 import 一次，通常由根模块或核心模块注册
@Global()
@Module({
    providers: [redisFactory],
    exports: [REDIS_CLIENT],
})
export class RedisModule {}
